#include "SampleSquare.h"
#include "GLUtils.h"
#include "LogUtils.h"

// 正方形/长方形

SampleSquare::SampleSquare() {

}

SampleSquare::~SampleSquare() {
}


void SampleSquare::LoadImage(NativeImage *pImage) {
    //null implement

}

void SampleSquare::Init() {

    char vShaderStr[] =
            "#version 300 es                          \n"
            "layout(location = 0) in vec4 vPosition;  \n"
            "layout(location = 1) in vec4 aColor;  \n"
            "out vec4 vColor;  \n"
            "void main()                              \n"
            "{                                        \n"
            "   gl_Position = vPosition;              \n"
            "   vColor = aColor;              \n"
            "}                                        \n";

    char fShaderStr[] =
            "#version 300 es                              \n"
            "precision mediump float;                     \n"
            "in vec4 vColor;                          \n"
            "out vec4 fragColor;                          \n"
            "void main()                                  \n"
            "{                                            \n"
            "   fragColor = vColor;  \n"
            "}                                            \n";

    m_ProgramObj = GLUtils::CreateProgram(vShaderStr, fShaderStr, m_VertexShader, m_FragmentShader);

}

void SampleSquare::Draw() {
    GLushort indices[6] = {0, 1, 2, 0, 2, 3};
    LOG_DEBUG("SampleSquare::Draw\n");

    if (m_ProgramObj == 0)
        return;

    // Use the program object
    glUseProgram(m_ProgramObj);

    // Load the vertex data
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, squareVertices);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, squareColorVertices);
    glEnableVertexAttribArray(1);

//    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(GLushort), GL_UNSIGNED_SHORT, indices);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

void SampleSquare::Destroy() {
    if (m_ProgramObj) {
        glDeleteProgram(m_ProgramObj);
    }
}

void SampleSquare::setParentViewSize(int w, int h) {
    m_ParentViewWidth = w;
    m_ParentViewHeight = h;

    GLfloat x = 0.5 * w / h;
    LOG_DEBUG("SampleSquare::setParentViewSize w:%d h:%d x%f \n", w, h, x);

    // 暂时： 通过计算使得长方形变成正方形
    // 后续通过矩阵来实现
    squareVertices[1] = squareVertices[10]  = x;
    squareVertices[4] = squareVertices[7] = 0-x;
}
void SampleSquare::OnSurfaceCreated() {

}
void SampleSquare::OnSurfaceChanged(int width, int height) {
    setParentViewSize(width, height);
}